// task_create_fill_in_vm.dart
import 'dart:ffi';

import 'package:flutter/foundation.dart';
import 'package:sjx/repository/model/config_model.dart';
import 'package:sjx/repository/sjx_api.dart';

import '../../../repository/model/task_detail_model.dart';
import '../../../repository/model/task_edit_detail_model.dart';
import '../../../repository/model/task_select_options_model.dart';
import 'model/task_step_model.dart';

class TaskCreateFillInViewModel with ChangeNotifier {
  final String? taskId;
  String taskCategoryStr;
  String? _taskTitleStr;
  String? _taskExplain;
  String? _taskPrice;
  String? _taskCount;
  double? _serviceFeePercent;

  bool againCreate = false;
  bool isLoading = true;
  bool hasChanged = false;
  bool agreedToTerms = false;

  String? taskDescription;
  List<TaskStepModel> taskSteps = [];
  String? taskRequirements;
  List<String> _taskRequirementImages = [];

  // 选项数据
  List<TaskSelectOptionsItemModel>? deviceOptions = [];
  List<TaskSelectOptionsItemModel>? bidTimesOptions = [];
  List<TaskSelectOptionsItemModel>? approveDurationOptions = [];
  List<TaskSelectOptionsItemModel>? submitDurationOptions = [];
  List<TaskSelectOptionsItemModel>? taskDurationOptions = [];
  List<String> guzhushenheOptionsDisplay = ['是', '否'];

  // 当前选择的值
  String deviceType = '';
  String bidTimesPerUser = '';
  String approveDuration = '';
  String submitDuration = '';
  String taskDuration = '';
  String requireOwnerApproval = '是';

  TaskCreateFillInViewModel({
    required this.taskCategoryStr,
    this.taskId,
  });

  double? get serviceFeePercent => _serviceFeePercent;
  String? get taskTitleStr => _taskTitleStr;
  String? get taskExplain => _taskExplain;
  String? get taskPrice => _taskPrice;
  String? get taskCount => _taskCount;
  List<String> get taskRequirementImages => _taskRequirementImages;

  void setTaskCategoryStr(String taskCategoryStrEx) {
    taskCategoryStr = taskCategoryStrEx;
  }
  Future<void> requestContent() async {
    isLoading = true;
    notifyListeners();

    try {
      // 获取选项数据
      final TaskSelectOptionsModel options = await SJXApi.instance().taskCreateSelectOptions(taskCategoryStr);

      // 设置默认值
      deviceOptions = options.deviceTypes;
      bidTimesOptions = options.bidTimesPerUserOptions;
      approveDurationOptions = options.approveDurationOptions;
      submitDurationOptions = options.submitDurationOptions;
      taskDurationOptions = options.taskDurationOptions;

      if (deviceOptions!.isNotEmpty) deviceType = deviceOptions!.first.optionValue;
      if (bidTimesOptions!.isNotEmpty) bidTimesPerUser = bidTimesOptions!.first.optionValue;
      if (approveDurationOptions!.isNotEmpty) approveDuration = approveDurationOptions!.first.optionValue;
      if (submitDurationOptions!.isNotEmpty) submitDuration = submitDurationOptions!.first.optionValue;
      if (taskDurationOptions!.isNotEmpty) taskDuration = taskDurationOptions!.first.optionValue;

      // 如果是编辑模式，获取任务详情
      if (taskId != null) {
        await _loadTaskDetail();
      }
    } catch (e) {
      // 处理错误
    } finally {
      isLoading = false;
      notifyListeners();
    }
  }

  Future<void> _loadTaskDetail() async {
    try {
      // 加载任务详情数据
      TaskEditDetailModel model = await SJXApi.instance().taskPublishDetail(taskId!);

      _serviceFeePercent = model.serviceFeePercent;
      // 填充表单数据
      _taskTitleStr = model.taskTitle;
      _taskExplain = model.taskDescription;
      taskRequirements = model.taskRequirement;
      _taskRequirementImages = model.taskRequirementImages ?? [];
      _taskPrice = model.sourceAmount.toString();
      _taskCount = model.originalBidTime.toString();

      // 设置选项值
      deviceType = model.deviceType;
      bidTimesPerUser = model.bidTimesByUser.toString();
      approveDuration = model.ownerApproveDurationHours.toString();
      submitDuration = model.bidSubmitDurationHours.toString();
      taskDuration = model.taskDurationHours.toString();
      requireOwnerApproval = model.approveByOwner ? '是' : '否';

      // 转换任务步骤
      taskSteps = _convertTaskSteps(model.taskStepList);

      // 标记表单已改变（用于检测是否需要保存）
      hasChanged = false;

      notifyListeners();

    } catch (e) {
      // 处理错误，可以显示错误提示
      print('加载任务详情失败: $e');
      // 可以显示错误提示
      // ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('加载任务详情失败')));
    }
  }

  // 将 API 返回的任务步骤转换为 TaskStepModel
  List<TaskStepModel> _convertTaskSteps(List<TaskStep> taskStepList) {
    List<TaskStepModel> steps = [];

    for (int i = 0; i < taskStepList.length; i++) {
      TaskStep step = taskStepList[i];
      TaskStepModel stepModel = TaskStepModel(
        sortValue: i,
        taskStepType: step.taskStepType,
        taskDescription: step.taskDescription ?? '',
      );

      // 根据步骤类型设置相应的字段
      switch (stepModel.taskStepType) {
        case 'CONTENT':
          stepModel.taskStepImages = step.taskStepImages ?? [];
          break;
        case 'LINK':
          stepModel.taskLinks = step.taskLinks?.isNotEmpty == true
              ? step.taskLinks!.first
              : '';
          break;
        case 'INFO':
          stepModel.taskCopyInfo = step.taskCopyInfo ?? '';
          break;
      }

      steps.add(stepModel);
    }

    return steps;
  }

  void setTaskRequirementImages(List<String> value) {
    _taskRequirementImages = value;
    notifyListeners();
  }

  void setTaskRequirement(String value) {
    taskRequirements = value;
    notifyListeners();
  }

  void setTitleChanged(String value) {
    _taskTitleStr = value;
  }

  void setExplainChanged(String value) {
    _taskExplain = value;
  }

  void setAgreedToTerms(bool value) {
    agreedToTerms = value;
    notifyListeners();
  }

  void setDeviceType(String value) {
    deviceType = value;
    notifyListeners();
  }

  void setBidTimesPerUser(String value) {
    bidTimesPerUser = value;
    notifyListeners();
  }

  void setApproveDuration(String value) {
    approveDuration = value;
    notifyListeners();
  }

  void setSubmitDuration(String value) {
    submitDuration = value;
    notifyListeners();
  }

  void setTaskDuration(String value) {
    taskDuration = value;
    notifyListeners();
  }

  void setRequireOwnerApproval(String value) {
    requireOwnerApproval = value;
    notifyListeners();
  }

  void setTaskDescription(String description) {
    taskDescription = description;
    hasChanged = true;
    notifyListeners();
  }

  void setTaskRequirements(String requirements) {
    taskRequirements = requirements;
    hasChanged = true;
    notifyListeners();
  }

  void addStep(TaskStepModel step) {
    step.sortValue = taskSteps.length;
    taskSteps.add(step);
    hasChanged = true;
    notifyListeners();
  }

  void updateStep(TaskStepModel step) {
    final index = taskSteps.indexWhere((s) => s.sortValue == step.sortValue);
    if (index != -1) {
      taskSteps[index] = step;
      hasChanged = true;
      notifyListeners();
    }
  }

  void removeStep(TaskStepModel step) {
    taskSteps.remove(step);
    // 重新排序
    for (int i = 0; i < taskSteps.length; i++) {
      taskSteps[i].sortValue = i;
    }
    hasChanged = true;
    notifyListeners();
  }

  void setAgainCreate(bool newAgainCreate) {
    againCreate = newAgainCreate;
  }

  Future<void> submitTask({
    required String title,
    required String explain,
    required String price,
    required String count,
    required Function(String) onSuccess,
    required Function(String) onError,
  }) async {
    try {
      // 构建提交数据 - 严格参照 iOS 代码结构
      final Map<String, dynamic> data = {
        'taskCategory': taskCategoryStr,
        'taskDescription': explain,
        'taskTitle': title,
        'sourceAmount': double.parse(price),
        'originalBidTime': int.parse(count),
        'taskRequirement': taskRequirements ?? '',
        'deviceType': deviceType,
        'bidTimesByUser': int.parse(bidTimesPerUser),
        'approveByOwner': requireOwnerApproval == '是', // 转换为布尔值
        'ownerApproveDurationHours': int.parse(approveDuration),
        'bidSubmitDurationHours': int.parse(submitDuration),
        'taskDurationHours': int.parse(taskDuration),
      };

      // 添加任务要求图片（如果有）
      if (_taskRequirementImages.isNotEmpty) {
        data['taskRequirementImages'] = _taskRequirementImages;
      }

      // 构建任务步骤 - 严格参照 iOS 代码结构
      List<Map<String, dynamic>> steps = [];
      for (int i = 0; i < taskSteps.length; i++) {
        TaskStepModel step = taskSteps[i];
        Map<String, dynamic> item = {
          'sortValue': i, // 使用当前索引作为排序值
          'taskStepType': step.taskStepType,
          'taskDescription': step.taskDescription,
        };

        // 根据步骤类型添加不同的字段
        if (step.taskStepType == 'LINK') {
          item['taskLinks'] = [step.taskLinks]; // iOS 代码中是数组形式
        } else if (step.taskStepType == 'INFO') {
          item['taskCopyInfo'] = step.taskCopyInfo;
        } else if (step.taskStepType == 'CONTENT') {
          if (step.taskStepImages != null && step.taskStepImages!.isNotEmpty) {
            item['taskStepImages'] = step.taskStepImages;
          }
        }

        steps.add(item);
      }
      data['taskStepCreateDtos'] = steps;

      if (taskId != null && !againCreate) {
        //编辑任务
        await SJXApi.instance().editTask(data, taskId!);
        onSuccess(taskId!);
      } else {
        // 创建新任务
        String taskNo = await SJXApi.instance().createTask(data);
        onSuccess(taskNo);
      }
    } catch (e) {
      onError(e.toString());
    }
  }
}